﻿using System;
using System.Collections.Generic;
using System.Text;
using DreamShield.Deployment.Driver.Indexer;
using DreamShield.Deployment.Miles.ApplicationUtils.ContextSwitch.DataTravelers;
using DreamShield.Deployment.Helpers;

namespace DreamShield.Deployment.Miles.ApplicationUtils.ContextSwitch
{
    /// <summary>
    /// Objet qui sera exécuté dans le domaine runtime distant, utilisé pour la communication
    /// avec DreamShield
    /// </summary>
    public sealed class DreamShieldRuntimeEndPoint : MarshalByRefObject
    {
        object sync = new object();

        /// <summary>
        /// Indique si l'application ayant le guid appGuid est installée
        /// </summary>
        /// <param name="appGuid"></param>
        /// <returns></returns>
        public bool IsInstalledApplication(Guid appGuid)
        {
            lock (sync)
            {
                return LocalProductIndexEntry.IsProductInstalled(appGuid);
            }
        }

        /// <summary>
        /// Obtient la liste des applications installées
        /// </summary>
        /// <returns></returns>
        public Guid[] GetInstalledApplications()
        {
            lock (sync)
            {
                return LocalProductIndexEntry.FindInstalledProducts();
            }
        }

        /// <summary>
        /// Obtient les informations concernant une application installée
        /// </summary>
        /// <param name="appGuid"></param>
        /// <returns></returns>
        public DT_InstalledApplicationInfos RetrieveApplicationInformations(Guid appGuid)
        {
            lock (sync)
            {
                if (!IsInstalledApplication(appGuid))
                    throw new ProductNotFoundException(appGuid.ToString());
                else
                {
                    ApplicationPackageInfo info = new ApplicationPackageInfo(appGuid);
                    try
                    {
                        DT_InstalledApplicationInfos result = new DT_InstalledApplicationInfos();

                        result.guid = appGuid;
                        result.author = info.Package.ProductAuthor;
                        result.company = info.Package.ProductCompany;
                        result.description = info.Package.ProductDescription;
                        result.name = info.Package.ProductName;
                        result.url = info.Package.ProductUrl;
                        result.version = info.Package.ProductVersion.StandardVersion;
                        result.installationlocation = info.Package.PackageTargetDir;

                        return result;
                    }
                    finally
                    {
                        info.Close();
                    }
                }
            }
        }
    }
}
